package com.apposcopy.ella.runtime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.location.Location;
import android.util.Log;

public class LocationReplayer extends Recorder {

	private final static String TAG = LocationReplayer.class.getSimpleName();
	public Location getLocation() throws MalformedURLException, IOException, JSONException{
		
		Log.d(TAG, "getLocation");
		URL url = new URL("http", "localhost", Ella.mockServerPort, "location");
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		
		try{
			conn.connect();
			StringBuilder sb = new StringBuilder();
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while((line = br.readLine()) != null){
				sb.append(line);
			}
			Log.d(TAG, "got location: " + sb.toString());
			JSONObject jsonLocation = new JSONObject(sb.toString());
			Location mockedLocation = new Location(jsonLocation.optString("Provider"));
			mockedLocation.setTime(jsonLocation.optLong("Time"));
			mockedLocation.setElapsedRealtimeNanos(jsonLocation.optLong("ElapsedRealtimeNanos"));
			mockedLocation.setLatitude(jsonLocation.optDouble("Latitude"));
			mockedLocation.setLongitude(jsonLocation.optDouble("Longitude"));
			mockedLocation.setAltitude(jsonLocation.optDouble("Altitude"));
			
			if(jsonLocation.optBoolean("hasSpeed")){
				mockedLocation.setSpeed((float)jsonLocation.optDouble("Speed"));
			}
			if(jsonLocation.optBoolean("hasBearing")){
				mockedLocation.setBearing((float) jsonLocation.optDouble("Bearing"));
			}
			return mockedLocation;
		}catch(IOException | JSONException e){
			throw e;
		}finally{
			conn.disconnect();
		}
		// TODO Add Location.extra
//			JSONObject jsonExtra = jsonLocation.optJSONObject("Extra");
//			if(jsonExtra != null){
//				Bundle extra = new Bundle();
//				while(jsonExtra.keys().hasNext()){
//					String key = jsonExtra.keys().next();
//					Object value = jsonExtra.get(key);
//				}
//			}
		
	}
	
}
